//
//  MJ_TaskViewController.m
//  UEAssistant
//
//  Created by mac on 2017/12/28.
//  Copyright © 2017年 youyixinxi. All rights reserved.
//

#import "MJ_TaskViewController.h"
#import "MJ_TaskViewModel.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "MJ_UserLoginViewModel.h"
#import "UIColor+Extend.h"
#import "LoginViewController.h"
#import "MJ_TaskTableViewCell.h"
#import "MJ_TaskCellLayout.h"
#import "MJ_SegmentButtonView.h"
#import "MJ_OrderDetailViewController.h"

static NSString *const orderCellIdf = @"orderCellIdf";

@interface MJ_TaskViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,MjSegmentViewDelegate>

@property (nonatomic, strong) UISegmentedControl *segment;

@property (nonatomic, strong) UITableView *tableView;

@property (strong, nonatomic) MJ_TaskViewModel *viewModel;

@property (strong, nonatomic) MJ_UserLoginViewModel *loginViewModel;
//当前选择任务类型
@property (assign, nonatomic)MJTaskOrder currentTaskOrderType;
//个人版页面时团队/平台的待抢单，进行中按钮
@property (strong, nonatomic)MJ_SegmentButtonView *btnView;
//新待抢任务数量（为了添加历史订单）
@property (assign, nonatomic)NSInteger newOrderCount;
//是否显示空数据提示页面
@property (assign, nonatomic)BOOL isShowEmpty;
//空数据时的提示语
@property (copy, nonatomic)NSString *emptyMessage;
@end

@implementation MJ_TaskViewController

#pragma mark --懒加载
- (MJ_TaskViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [[MJ_TaskViewModel alloc] init];
    }
    return _viewModel;
}
- (MJ_UserLoginViewModel *)loginViewModel {
    if (!_loginViewModel) {
        _loginViewModel = [[MJ_UserLoginViewModel alloc] init];
    }
    return _loginViewModel;
}

- (MJ_SegmentButtonView *)btnView {
    if (!_btnView) {
        _btnView = [[MJ_SegmentButtonView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, 40)];
        _btnView.delegate = self;
    }
    return _btnView;
}


#pragma mark --
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc]init];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self setupUI];
}

- (void)initializeDataSource {
    TGLog(@"当前用户等级 ------------- %zd", CurrentUserType);
    _emptyMessage = @"暂时没有合适你的任务";
    switch (CurrentUserType) {
        case 4:
            //如果是个人用户
            _currentTaskOrderType = MJTaskOrderWaitWithGroup;
            [self.view addSubview:self.btnView];
            break;
        case 5:
            _currentTaskOrderType = MJTaskOrderWaitWithGroup;
            [self.view addSubview:self.btnView];
            break;
            //企业用户
        default:
            _currentTaskOrderType = MJTaskOrderEnterpriseWait;
            break;
    }
    [self autoLogin];
}
//自动登录
- (void)autoLogin {
    
    [LSProgressHUD showLoadingToView:self.navigationController.view];
    [self.loginViewModel autoLoginWithResult:^(BOOL success) {
        
        if (success) {
            [LSProgressHUD hideForView:self.navigationController.view];
            [self loadDataWithParameter:@{@"task_status":@"0,1"}];
        }else{
            [[MJ_UserMessage sharedInstance] userLogOut];
            [UIApplication sharedApplication].keyWindow.rootViewController = [LoginViewController new];
            [LSProgressHUD hideForView:self.navigationController.view];
        }
    }];
}

#pragma mark --UI初始化
- (void)setupUI {
    
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc]init];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createSegmentControl];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height-64-44) style:UITableViewStylePlain];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopic)];
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
    [_tableView registerClass:[MJ_TaskTableViewCell class] forCellReuseIdentifier:orderCellIdf];
    _tableView.mj_header.automaticallyChangeAlpha = YES;
    _tableView.emptyDataSetSource = self;
    _tableView.emptyDataSetDelegate = self;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [UIView new];
    _tableView.mj_footer.automaticallyChangeAlpha = YES;
    _tableView.mj_header.backgroundColor = RGB(245, 246, 247, 1);
    _tableView.separatorColor = [UIColor colorWithHexString:@"e0e0e0"];
    [self.view addSubview:_tableView];
    
    //如果是个人用户，则区分团队和平台的待接单和进行中
    if (CurrentUserType == 4 || CurrentUserType == 5) {
        [self.view addSubview:self.btnView];
        _tableView.frame = CGRectMake(0, 40, Screen_Width, Screen_Height-64-40-44);
    }
}
//添加分段控制器
- (void)createSegmentControl{
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    NSArray *array = [NSArray arrayWithObjects:@"待抢单",@"进行中", nil];
    if (CurrentUserType == 4 || CurrentUserType == 5) {
        array = @[@"团队",@"平台"];
    }
    _segment = [[UISegmentedControl alloc]initWithItems:array];
    _segment.frame = CGRectMake(10, 100, 152*Radio, 28);
    _segment.center = CGPointMake(self.view.center.x, 20);
    NSDictionary *selected = @{NSFontAttributeName:[UIFont systemFontOfSize:11],
                               NSForegroundColorAttributeName:[UIColor whiteColor]};
    NSDictionary *normal = @{NSFontAttributeName:[UIFont systemFontOfSize:11],
                             NSForegroundColorAttributeName:RGB(133, 136, 146, 1)};
    [_segment setTitleTextAttributes:normal forState:UIControlStateNormal];
    [_segment setTitleTextAttributes:selected forState:UIControlStateSelected];
    _segment.tintColor = RGB(133, 136, 146, 1);
    _segment.selectedSegmentIndex = 0;
    [_segment addTarget:self action:@selector(SelectTeamCliced:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = _segment;
}

#pragma mark --协议

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.viewModel.resultModelList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {
    
    MJ_TaskTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:orderCellIdf];
    if (!cell) {
        cell = [[MJ_TaskTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:orderCellIdf];
    }
    MJ_TaskCellLayout *layout = self.viewModel.resultModelList[indexPath.row];
    cell.cellLayout = layout;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MJ_TaskCellLayout *layout = self.viewModel.resultModelList[indexPath.row];
    return layout.cellHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, tableView.sectionHeaderHeight)];
    headView.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return  15;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MJ_TaskCellLayout *layout = self.viewModel.resultModelList[indexPath.row];
    if (layout.isHistoryOrder) {
        return;
    }
    if (_currentTaskOrderType == MJTaskOrderWaitWithPlat ||
        _currentTaskOrderType == MJTaskOrderWaitWithGroup ||
        _currentTaskOrderType == MJTaskOrderEnterpriseWait ||
        _currentTaskOrderType == MJTaskOrderOngoingWithPlat ||
        _currentTaskOrderType == MJTaskOrderTranslateExample) {
        
        MJ_OrderDetailViewController *vc = [[MJ_OrderDetailViewController alloc] init];
        MJ_TaskCellLayout *layout = self.viewModel.resultModelList[indexPath.row];
        //去除未读标记
//        if (layout.resultModel.isRead && [layout.resultModel.isRead isEqualToString:@"0"]) {
//            layout.resultModel.isRead = @"1";
//            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//            [self hideBlueRoundIconWithModel:layout.resultModel type:_currentTaskOrderType];
//        }
        vc.currentType = _currentTaskOrderType;
        vc.resultModel = layout.resultModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

//隐藏新内容标记。。。
- (void)hideBlueRoundIconWithModel:(MJ_TaskListResult *)model type:(MJTaskOrder)type {
    NSString *urlString;
    urlString = [userManager.urlCategate stringByAppendingString:readDetail_connector];
    NSDictionary *dic = @{@"sectorId":[NSString stringWithFormat:@"%.0lf",model.sector_id],
                          @"ownerId":[NSString stringWithFormat:@"%.0lf",model.owner_id],
                          @"taskId":[NSString stringWithFormat:@"%.0lf",model.task_id]};
    //查看后取消蓝点
    [AvailableNetWorking postWithUrl:urlString params:dic successHandler:^(id responseObject) {
        TGLog(@"%@",responseObject);
    } falureHandler:^(NSError *error) {
    }];
}

#pragma mark --空数据处理
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"任务"];
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSString *text = _emptyMessage;
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:16.0f],
                                 NSForegroundColorAttributeName: [UIColor darkGrayColor]};
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    
    return _isShowEmpty;
}
#pragma mark -- 上下拉刷新
- (void)loadNewTopic {
    self.viewModel.currentPage = 0;
    [self.viewModel.resultModelList removeAllObjects];
    [self loadDataWithParameter:@{@"task_status":@"0,1"}];
}

- (void)loadMoreTopic {
    [self loadDataWithParameter:@{@"task_status":@"0,1"}];
}

#pragma mark --数据加载
//分段控制器选择
- (void)SelectTeamCliced:(UISegmentedControl *)sender {
    
    _emptyMessage = @"暂时没有合适你的任务";
    //先清空原数据
    [self.viewModel.resultModelList removeAllObjects];
    self.viewModel.currentPage = 0;
    //个人版
    if (CurrentUserType == 4 || CurrentUserType == 5) {
        switch (_segment.selectedSegmentIndex) {
            case 0://点击团队
                self.btnView.isGroupSelected = YES;
                self.btnView.selectedIndex = 0;
                [self clickSegmentBtnWithType:MJSegmentTypeWaitOrder];
                break;
            default://点击平台
            {
                self.btnView.isGroupSelected = NO;
                self.btnView.selectedIndex = 0;
                if (shareData.isPoolTranslator == 0) {
                    _emptyMessage = @"您不是译马网人才库的成员，不能承接来自平台的稿件。若有意加入译马网人才库，请先申请成为认证译员，方法是：登录网页端，前往【我的账号】>【翻译信息】，点击语言对上的“申请认证”按钮，即可申请认证。";
                    [_tableView reloadData];
                }else{
                    [self clickSegmentBtnWithType:MJSegmentTypeWaitOrder];
                }
            }
                break;
        }
    }else{
        //企业版
        switch (_segment.selectedSegmentIndex) {
            case 0:
                _currentTaskOrderType = MJTaskOrderEnterpriseWait;
                break;
            default:
                _currentTaskOrderType = MJTaskOrderEnterpriseOngoing;
                break;
        }

        //请求数据
        [self loadDataWithParameter:@{@"task_status":@"0,1"}];
    }

}

/**仅为个人版本时，分团队和平台的待接单和进行中*/
- (void)clickSegmentBtnWithType:(MJSegmentType)type {
    
    switch (type) {
        case MJSegmentTypeWaitOrder://个人版待接单
            
            if (_segment.selectedSegmentIndex == 0) {
                //来自团队待接单
                _currentTaskOrderType = MJTaskOrderWaitWithGroup;
                
            }else{
                //来自平台待接单
                _currentTaskOrderType = MJTaskOrderWaitWithPlat;
            }
            break;
        case MJSegmentTypeTranslation://试译中
            
            _currentTaskOrderType = MJTaskOrderTranslateExample;
            break;
        default:
            if (_segment.selectedSegmentIndex == 0) {
                //来自团队进行中
                _currentTaskOrderType = MJTaskOrderOngoingWithGroup;
                
            }else{
                //来自平台进行中
                _currentTaskOrderType = MJTaskOrderOngoingWithPlat;
            }
            break;
    }
    //如果是平台任务，且不是译马网人才库成员，则不进行网络请求
    if (_currentTaskOrderType == MJTaskOrderOngoingWithPlat || _currentTaskOrderType == MJTaskOrderWaitWithPlat) {
        if (shareData.isPoolTranslator == 0) {
            _emptyMessage = @"您不是译马网人才库的成员，不能承接来自平台的稿件。若有意加入译马网人才库，请先申请成为认证译员，方法是：登录网页端，前往【我的账号】>【翻译信息】，点击语言对上的“申请认证”按钮，即可申请认证。";
            [_tableView reloadData];
            return;
        }
    }
    //请求数据
    if (_currentTaskOrderType == MJTaskOrderOngoingWithPlat) {
        [self loadDataWithParameter:@{@"status":@"1"}];
    }else if (_currentTaskOrderType == MJTaskOrderTranslateExample) {
        [self loadDataWithParameter:@{@"pagecount":@"0"}];
    }
    else{
        [self loadDataWithParameter:@{@"task_status":@"0,1"}];
    }
    
}
#pragma mark --网络请求

- (void)loadDataWithParameter:(NSDictionary *)parameter{
    
    if (self.tableView.mj_header.isRefreshing || self.tableView.mj_footer.isRefreshing) {
    }else{
        [LSProgressHUD showLoadingToView:self.navigationController.view];
    }

    __weak typeof(self) weakSelf = self;
    [self.viewModel getTaskOrderListWith:_currentTaskOrderType parameter:parameter success:^(BOOL success) {
        
        __strong typeof(weakSelf) sself = weakSelf;
        //是否显示空数据
        _isShowEmpty = self.viewModel.resultModelList.count == 0 ? YES:NO;
        //判断是否还有更多数据
        if (sself.viewModel.hasMore) {
            [sself.tableView.mj_footer endRefreshing];
        }else{
            [sself.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        _newOrderCount = sself.viewModel.resultModelList.count;
        //如果订单数量不足8个，则请求历史订单（团队待抢单）
        if (_currentTaskOrderType == MJTaskOrderWaitWithGroup || _currentTaskOrderType == MJTaskOrderEnterpriseWait)  {
            if (sself.viewModel.resultModelList.count < 8) {
                [sself.viewModel getHistoryOrderListWithType:_currentTaskOrderType parameter:@{@"pageSize":@"8",@"pageNum":@"1"} success:^(BOOL success) {
                    [sself.tableView.mj_header endRefreshing];
                    [LSProgressHUD hideForView:sself.navigationController.view];
                    [sself.tableView reloadData];
                }];
            }else{
                [sself.tableView.mj_header endRefreshing];
                [LSProgressHUD hideForView:sself.navigationController.view];
                [sself.tableView reloadData];
            }
        }else{
            [sself.tableView.mj_header endRefreshing];
            [LSProgressHUD hideForView:sself.navigationController.view];
            [sself.tableView reloadData];
        }
    }];

}
@end
